package org.adream.account.util;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.adream.account.service.ADreamServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.ResourcePropertySource;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;

public class SDKTestSendTemplateSMS {
	
	public static final SDKTestSendTemplateSMS instance = new SDKTestSendTemplateSMS();

	Logger log = LoggerFactory.getLogger(getClass());
	
	SmsClient client = null;
	
	private SDKTestSendTemplateSMS(){
		String appid=null,appkey=null;
		try {
			log.info("正在读取sms配置文件");
			ResourcePropertySource rps = new ResourcePropertySource("classpath:/config/sms.properties");
			appid = String.valueOf(rps.getProperty("telnet.sms.appid"));
			appkey = String.valueOf(rps.getProperty("telnet.sms.appkey"));
			log.info("appid:" + appid);
			
		} catch (IOException e) {
			throw new Error("无法读取sms。properties",e);
		}
		Credential cred = new Credential(appid, appkey);
		HttpProfile httpProfile = new HttpProfile();
        httpProfile.setReqMethod("POST");
        httpProfile.setConnTimeout(60);
        httpProfile.setEndpoint("sms.tencentcloudapi.com");
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setSignMethod("HmacSHA256");
        clientProfile.setHttpProfile(httpProfile);
        client = new SmsClient(cred, "ap-beijing",clientProfile);
	}
	
	/**
	 * @param args
	 * @return 
	 * @throws ADreamServiceException 
	 * @throws ALBusinessException 
	 */
	public HashMap<String, Object> sendMSMinfo(String phone,String code,String checkCode,HttpServletRequest request) throws ADreamServiceException {
		HashMap<String, Object> result = null;
		
		Object sessionCode = request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		request.getSession().removeAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		log.info("checkCode:"+checkCode);
		log.info("sessionCode:"+sessionCode);
		
		if(!Constant.NOT_NEED_CHECK_CODE.equals(checkCode) && !checkCode.trim().toLowerCase().equals(String.valueOf(sessionCode).trim().toLowerCase())){
			result = new HashMap<String, Object>();
			result.put("statusCode", "ABCDEFG");
			result.put("statusMsg", "验证码输入错误");			
			return result;
		}
		
		return sendMSMinfoNoCheck(phone,code);
	}

	/**
	 * @param args
	 * @return 
	 * @throws ADreamServiceException 
	 * @throws ALBusinessException 
	 */
	public HashMap<String, Object> sendMSMinfoNoCheck(String phone,String code) throws ADreamServiceException {
		HashMap<String, Object> result = new HashMap<String,Object>(4);
		
		SendSmsRequest req = new SendSmsRequest();

        String sdkAppId = "1400481142";
        req.setSmsSdkAppid(sdkAppId);

        String signName = "真爱梦想";
        req.setSign(signName);
        
        String templateId = "1286172";
        req.setTemplateID(templateId);
        String[] phoneNumberSet = {"+86"+phone};
        req.setPhoneNumberSet(phoneNumberSet);

        /* 模板参数: 若无模板参数，则设置为空 */
        String[] templateParamSet = {code,"3"};
        req.setTemplateParamSet(templateParamSet);

        /* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
         * 返回的 res 是一个 SendSmsResponse 类的实例，与请求对象对应 */
        SendSmsResponse res;
		try {
			res = client.SendSms(req);
			 // 输出json格式的字符串回包
	        log.debug(SendSmsResponse.toJsonString(res));
	        
			SendStatus sss[] = res.getSendStatusSet();
			for(SendStatus ss:sss){
				if("Ok".equals(ss.getCode())){
					result.put("statusCode", "000000");
					return result;
				}else{
					log.info("sendMsgWrong:");
					log.info("phone:"+phone);
					log.info("msg:" + ss.getCode() + "***:" + ss.getMessage());
					result.put("statusCode", ss.getCode());
					result.put("statusMsg", "短信发送出错，请联系管理员。");
					return result;
				}
			}
		} catch (TencentCloudSDKException e) {
			log.warn(e.getMessage());
			throw new ADreamServiceException(e.toString());
		}
		result.put("statusCode", "ABCDEF");
		result.put("statusMsg", "未获取到发送短信成功与否的状态值");
		return result;
	}
}
